﻿namespace EyeOpen.Combinatorics.Mvc.Controllers
{
	using System.Linq;
	using System.Web.Mvc;
	using EyeOpen.Combinatorics.Mvc.Models;
	using EyeOpen.Math.Combinatorics;

	public class HomeController : Controller
	{
		public ActionResult Index()
		{
			var names = string.Join(",", Enumerable.Range(1, 10).Select(n => "Team" + n));

			return View(new TeamModelQuery { Names = names, Groups = 2 });
		}

		[HttpPost]
		public ActionResult Index(TeamModelQuery teamModelQuery)
		{
			if (!ModelState.IsValid)
			{
				return Render("Index", teamModelQuery);
			}

			var teamModelResult = 
				new TeamModelResult
			    {
					Matches =
					new Combination<string>(teamModelQuery.Groups, teamModelQuery.Names.Replace(" ", string.Empty).Split(','))
					.ToList()
					.Randomize()
			    };

			return Render("Matches", teamModelResult);
		}

		private ActionResult Render(string viewName, object model)
		{
			if (Request.IsAjaxRequest())
			{
				return PartialView(viewName, model);
			}

			return View(viewName, model);
		}
	}
}